/*
 * Copyright (C) 2008 by The Regents of the University of California
 * Redistribution of this file is permitted under the terms of the GNU
 * Public License (GPL).
 *
 * @author Junghoo "John" Cho <cho AT cs.ucla.edu>
 * @date 3/24/2008
 */
 
#include "BTreeIndex.h"
#include "BTreeNode.h"

//!!!!!!!!!!just for test
#include "iostream"

using namespace std;

/*
 * BTreeIndex constructor
 */
BTreeIndex::BTreeIndex()
{
    rootPid = -1;
	treeHeight = -1;
}

/*
 * Open the index file in read or write mode.
 * Under 'w' mode, the index file should be created if it does not exist.
 * @param indexname[IN] the name of the index file
 * @param mode[IN] 'r' for read, 'w' for write
 * @return error code. 0 if no error
 */
RC BTreeIndex::open(const string& indexname, char mode)
{
	openMode = mode;
    RC rc = pf.open(indexname, mode);
	char buffer[PageFile::PAGE_SIZE];
	if(pf.read(0, buffer) == 0)
	{
		rootPid = *((int*)buffer);
		treeHeight = *((int*)(buffer+4));
		return rc;
	}
	if(mode == 'r')
		return rc;
	
	
	//if empty, create a root and a leaf

	pf.write(0, buffer);
	rootPid = 1;
	PageId leafPid = 2;
	treeHeight = 1;
	BTNonLeafNode root;
	BTLeafNode	leaf;
	root.setLeftPtr(leafPid);
	root.write(rootPid, pf);
	leaf.write(leafPid, pf);

	return rc;
}

/*
 * Close the index file.
 * @return error code. 0 if no error
 */
RC BTreeIndex::close()
{
	if(openMode == 'w')
	{
		char buffer[PageFile::PAGE_SIZE];
		*((int*)buffer) = rootPid;
		*((int*)(buffer+4)) = treeHeight;
		pf.write(0, buffer); 
	}
    return pf.close();
}

/*
 * Insert (key, RecordId) pair to the index.
 * @param key[IN] the key for the value inserted into the index
 * @param rid[IN] the RecordId for the record being inserted into the index
 * @return error code. 0 if no error
 */
RC BTreeIndex::insert(int key, const RecordId& rid)
{
    IndexCursor leafCursor;
	locate(key, leafCursor);
	BTLeafNode leaf;
	leaf.read(leafCursor.pid, pf);
	if(leaf.insert(key, rid) == 0)
	{
		leaf.write(leafCursor.pid, pf);
		return 0;
	}
	BTLeafNode sib;
	int sibKey;
	leaf.insertAndSplit(key, rid, sib, sibKey);
	PageId sibPid = pf.endPid();
	sib.setNextNodePtr(leaf.getNextNodePtr());
	leaf.setNextNodePtr(sibPid);
	leaf.write(leafCursor.pid, pf);
	sib.write(sibPid, pf);
	insertInParent(leafCursor.pid, sibKey, sibPid);
}

RC BTreeIndex::insertInParent(PageId leftPid, int midKey, PageId rightPid)
{
	if(leftPid == rootPid)
	{
		BTNonLeafNode root;
		root.setLeftPtr(leftPid);
		root.insert(midKey, rightPid);
		PageId newPid = pf.endPid();
		rootPid = newPid;
		root.write(newPid, pf);
		treeHeight++;
	}
	int height = treeHeight;
	int nodepid = rootPid;
	int parentPid = rootPid;
	BTNonLeafNode nonleaf;
	while(height > 0)
	{
		nonleaf.read(nodepid, pf);
		parentPid = nodepid;
		nonleaf.locateChildPtr(midKey, nodepid);
		if(nodepid == leftPid)
			break;
		height--;
	}
	nonleaf.read(parentPid, pf);
	if(nonleaf.insert(midKey, rightPid) == 0)
	{
		nonleaf.write(parentPid, pf);
		return 0;
	}
	BTNonLeafNode sib;
	int sibKey;
	nonleaf.insertAndSplit(midKey, rightPid, sib, sibKey);
	PageId sibPid = pf.endPid();
	nonleaf.write(parentPid, pf);
	sib.write(sibPid, pf);
	insertInParent(parentPid, sibKey, sibPid);
	
}




/*
 * Find the leaf-node index entry whose key value is larger than or 
 * equal to searchKey, and output the location of the entry in IndexCursor.
 * IndexCursor is a "pointer" to a B+tree leaf-node entry consisting of
 * the PageId of the node and the SlotID of the index entry.
 * Note that, for range queries, we need to scan the B+tree leaf nodes.
 * For example, if the query is "key > 1000", we should scan the leaf
 * nodes starting with the key value 1000. For this reason,
 * it is better to return the location of the leaf node entry 
 * for a given searchKey, instead of returning the RecordId
 * associated with the searchKey directly.
 * Once the location of the index entry is identified and returned 
 * from this function, you should call readForward() to retrieve the
 * actual (key, rid) pair from the index.
 * @param key[IN] the key to find.
 * @param cursor[OUT] the cursor pointing to the first index entry
 *                    with the key value.
 * @return error code. 0 if no error.
 */
RC BTreeIndex::locate(int searchKey, IndexCursor& cursor)			//!!!!!!height starts from 0, if only with root and leaf, then height is 1
{	
	cursor.pid = -1;
	cursor.eid = -1;																
	//cout << "height " << treeHeight << endl;
	int height = treeHeight;
	int nodepid = rootPid;
	BTNonLeafNode nonleaf;
	while(height > 0)
	{
		nonleaf.read(nodepid, pf);
		nonleaf.locateChildPtr(searchKey, nodepid);
		height--;
	}
	BTLeafNode leaf;
	leaf.read(nodepid, pf);
	//cout << "nodepid " << nodepid << endl;
	int entryid;
	RC rc;
	rc = leaf.locate(searchKey, entryid);
	cursor.pid = nodepid;
	cursor.eid = entryid;
	return rc;
}

/*
 * Read the (key, rid) pair at the location specified by the index cursor,
 * and move foward the cursor to the next entry.
 * @param cursor[IN/OUT] the cursor pointing to an leaf-node index entry in the b+tree
 * @param key[OUT] the key stored at the index cursor location.
 * @param rid[OUT] the RecordId stored at the index cursor location.
 * @return error code. 0 if no error
 */
RC BTreeIndex::readForward(IndexCursor& cursor, int& key, RecordId& rid)
{
    if(cursor.pid >= pf.endPid() || cursor.pid < 0)
		return RC_INVALID_CURSOR;
	BTLeafNode leaf;
	leaf.read(cursor.pid, pf);
	RC rc = leaf.readEntry(cursor.eid, key, rid);
	if(rc != 0)
		return rc;
	if(cursor.eid+1 == leaf.getKeyCount())
	{
		cursor.eid = 0;
		cursor.pid = leaf.getNextNodePtr();
		return 0;
	}
	else
	{
		cursor.eid += 1;
		return 0;
	}
}
